﻿using System;
using System.Collections.Generic;
using System.IO;
using ProtoBuf;
using System.ComponentModel;
namespace Model
{
    public static  class ProtobufHelper
    {
        public static byte[] ToBytes(object message)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.Serialize(ms, message);
                return ms.ToArray();
            }
        }

        public static object FromBytes(Type t,byte[] bytes,int index,int length)
        {
            object obj;
            using (MemoryStream ms= new MemoryStream(bytes,index,length))
            {
               obj =  Serializer.Deserialize(t,ms);
            }
            ISupportInitialize supportInitialize = obj as ISupportInitialize;
            if (supportInitialize == null)
            {
                return obj;
            }
            supportInitialize.EndInit();
            return obj;
        }

        public static T FromBytes<T>(byte[] bytes)
        {
            T t;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
               t =  Serializer.Deserialize<T>(ms);
            }

            ISupportInitialize supportInitialize = t as ISupportInitialize;
            if(supportInitialize == null)
            {
                return t;
            }
            supportInitialize.EndInit();
            return t;
        }

        public static T FromBytes<T>(byte[] bytes,int index,int length)
        {
            T t;
            using (MemoryStream ms = new MemoryStream(bytes,index,length))
            {
                t = Serializer.Deserialize<T>(ms);
            }

            ISupportInitialize supportInitialize = t as ISupportInitialize;
            if (supportInitialize == null)
            {
                return t;
            }
            supportInitialize.EndInit();
            return t;
        }

    }
}
